<template>
    <div class="background-image">
        <div class="login-form component-background">
            <div class="wrapper">
                <div class="card-switch">
                    <label class="switch">
                        <input type="checkbox" class="toggle">
                        <span class="slider"></span>
                        <span class="card-side"></span>
                        <div class="flip-card__inner">
                            <div class="flip-card__front">
                                <div class="title">用户登录</div>
                                <form class="flip-card__form" @submit.prevent="toHome">
                                    <input v-model="username" class="flip-card__input" name="text" placeholder="请输入你的账号" type="text">
                                    <input v-model="password" class="flip-card__input" name="password" placeholder="请输入密码" type="password" show-password>
                                    <div class="button-container">
                                        <span class="register-link" @click="toRegister()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注册</span>
                                        <button class="flip-card__btn" @click="toHome">用户登录</button>
                                        <span class="forgot-password-link" @click="forgetPassword()">忘记密码？</span>
                                    </div>
                                </form>
                            </div>
                            <div class="flip-card__back">
                                <div class="title">管理员登录</div>
                                <form class="flip-card__form" @submit.prevent="handleAdminLogin">
                                    <input v-model="adminUsername" class="flip-card__input" name="text" placeholder="请输入你的管理员账号" type="text">
                                    <input v-model="adminPassword" class="flip-card__input" name="password" placeholder="请输入密码" type="password" show-password>
                                    <button class="flip-card__btn" @click="toAdminPage()">管理员登录</button>
                                </form>
                            </div>
                        </div>
                    </label>
                </div>
            </div>
        </div>
        <footer>
            <p>网站作者：恐怖大魔王——————郑舔橙</p>
        </footer>
        <!-- 遮罩层 -->
        <div v-if="loading" class="loading-overlay">
            <loading/>
        </div>
    </div>
</template>


<script>
import {deptlist, getMyGoodTipId, getMySelf, userLogin,adminLogin} from "@/api/api";
import store from "@/store";
import loading from "@/components/Loading.vue";
import {websocketUrl} from "@/api/baseUrl";
export default {
    name: 'Login',
    components: {
        loading
    },
    data() {
        return {
            adminUsername:'',
            adminPassword:'',
            username: '',
            password: '',
            rememberMe: false,
            loading: false, // 加载状态变量
            websocket: null,
            isNavigating: false // 添加导航状态标记
        };
    },
    methods: {
        async toHome() {
            // 避免重复点击
            if (this.loading || this.isNavigating) return;

            this.loading = true; // 开始加载
            try {
                const response = await userLogin({
                    UserEmail: this.username,
                    UserPassWord: this.password
                });
                console.log('API 响应:', response); // 调试输出
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success("登录成功");

                    // 使用store的actions来处理登录，这会同时设置用户名和token
                    await this.$store.dispatch('login', {   
                        username: this.username,
                        token: response.data.data
                    });
                    console.log('用户数据:',localStorage.getItem('Authorization'))
                    // 存储本地浏览状态
                    localStorage.setItem('browseState', JSON.stringify({
                        currentPage: 1,
                        pageSize: 10,
                        sortBy: 'time',
                        order: 'desc'
                    }));

                    // 获取用户数据
                    this.fetchUserData();

                    // 建立 WebSocket 连接
                    setTimeout(() => {
                        // 建立 WebSocket 连接
                        this.websocket = new WebSocket(websocketUrl);

                        // 先设置所有事件处理程序
                        this.websocket.onopen = () => {
                            console.log('WebSocket连接已建立');

                            // 确保WebSocket已完全连接再发送消息
                            if (this.websocket.readyState === WebSocket.OPEN) {
                                this.websocket.send(JSON.stringify({
                                    type: 'authenticate',
                                    token: this.$store.state.Authorization
                                }));
                            } else {
                                console.warn('WebSocket尚未完全连接，等待连接完成后再发送认证消息');
                                // 使用setTimeout确保WebSocket已连接
                                setTimeout(() => {
                                    if (this.websocket.readyState === WebSocket.OPEN) {
                                        this.websocket.send(JSON.stringify({
                                            type: 'authenticate',
                                            token: this.$store.state.Authorization
                                        }));
                                        console.log('延迟后发送WebSocket认证消息');
                                    } else {
                                        console.error('WebSocket连接失败，无法发送认证消息');
                                    }
                                }, 300);
                            }
                        };

                        this.websocket.onmessage = (event) => {
                            console.log('WebSocket收到消息:', event.data);
                            // 基本消息处理
                            try {
                                const message = JSON.parse(event.data);
                                if (message.type === 'authenticated') {
                                    console.log('用户已验证');
                                } else if (message.type === 'authentication_failed') {
                                    console.error('用户验证失败');
                                    this.websocket.close();
                                }
                            } catch (error) {
                                console.error('解析WebSocket消息出错:', error);
                            }
                        };

                        this.websocket.onerror = (error) => {
                            console.error('WebSocket错误:', error);
                            this.$message.error("WebSocket 连接失败，请稍后再试");
                        };

                        this.websocket.onclose = () => {
                            console.log('WebSocket连接已关闭');
                            this.$store.state.websocket = null;
                        };

                        // 最后再设置到store中
                        this.$store.state.websocket = this.websocket;
                    }, 500); // 延迟500毫秒确保token已设置

                    // WebSocket错误处理已移至setTimeout中

                    // 获取用户收藏的帖子
                    const GoodsTip = await getMyGoodTipId();
                    this.$store.commit('setMyGoodTips', GoodsTip.data.data);

                    // 获取部门列表
                    const deptList = await deptlist();
                    if (deptList.data.message === "成功") {
                        const defaultDept = { dept_id: 0, dept_name: "不带tag" };
                        const existingDepts = deptList.data.data;
                        // 检查默认对象是否已经存在
                        const hasDefaultDept = existingDepts.some(dept => dept.dept_id === defaultDept.dept_id);
                        if (!hasDefaultDept) {
                            existingDepts.unshift(defaultDept);
                        }
                        this.$store.commit('setDeptList', existingDepts);
                    }
                } else {
                    this.$message.error("登录失败");
                    this.loading = false;
                    this.isNavigating = false; // 登录失败时重置导航标记
                }
            } catch (error) {
                console.error('登录时出错:', error);
                this.$message.error("登录失败，请稍后再试");
                this.loading = false;
                this.isNavigating = false; // 登录失败时重置导航标记
            }
        },
        fetchUserData() {
            getMySelf().then((me) => {
                store.state.me = me.data.data;
                // 避免重复导航
                if (this.isNavigating) return;

                this.isNavigating = true; // 标记导航开始
                // 使用replace而不是push，避免导航守卫重定向问题
                this.$router.replace('/Main/home').finally(() => {
                    // 在路由跳转完成后再结束loading状态
                    setTimeout(() => {
                        this.loading = false;
                        this.isNavigating = false; // 导航完成后重置标记
                    }, 300);
                });
            }).catch((error) => {
                console.error('获取用户信息失败:', error);
                this.$message.error("获取用户信息失败，请稍后再试");
                this.loading = false;
            });
        },
        toRegister() {
            this.$router.push('/register');
        },
        forgetPassword(){
            this.$router.push('/login/forgetPassword');
        },
        async toAdminPage() {
            // 避免重复点击
            if (this.loading || this.isNavigating) return;

            this.loading = true; // 开始加载
            try {
                const response = await adminLogin({
                    UserEmail: this.adminUsername,
                    UserPassWord: this.adminPassword
                });
                console.log('API 响应:', response); // 调试输出
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success("登录成功");

                    // 使用store的actions来处理登录，这会同时设置用户名和token
                    this.$store.dispatch('login', {
                        username: this.adminUsername,
                        token: response.data.data.token
                    });

                    this.fetchAdminData();
                } else {
                    this.$message.error("登录失败");
                    this.loading = false;
                    this.isNavigating = false; // 登录失败时重置导航标记
                }
            } catch (error) {
                console.error('登录时出错:', error);
                this.$message.error("登录失败，请稍后再试");
                this.loading = false;
                this.isNavigating = false; // 登录失败时重置导航标记
            }
        },
        fetchAdminData() {
            getMySelf().then((me) => {
                store.state.me = me.data.data;

                // 管理员也需要WebSocket连接
                setTimeout(() => {
                    // 建立 WebSocket 连接
                    this.websocket = new WebSocket(websocketUrl);

                    // 先设置所有事件处理程序
                    this.websocket.onopen = () => {
                        console.log('管理员WebSocket连接已建立');

                        // 确保WebSocket已完全连接再发送消息
                        if (this.websocket.readyState === WebSocket.OPEN) {
                            this.websocket.send(JSON.stringify({
                                type: 'authenticate',
                                token: this.$store.state.Authorization
                            }));
                        } else {
                            console.warn('管理员WebSocket尚未完全连接，等待连接完成后再发送认证消息');
                            // 使用setTimeout确保WebSocket已连接
                            setTimeout(() => {
                                if (this.websocket.readyState === WebSocket.OPEN) {
                                    this.websocket.send(JSON.stringify({
                                        type: 'authenticate',
                                        token: this.$store.state.Authorization
                                    }));
                                    console.log('延迟后发送管理员WebSocket认证消息');
                                } else {
                                    console.error('管理员WebSocket连接失败，无法发送认证消息');
                                }
                            }, 300);
                        }
                    };

                    this.websocket.onmessage = (event) => {
                        console.log('WebSocket收到消息:', event.data);
                        // 基本消息处理
                        try {
                            const message = JSON.parse(event.data);
                            if (message.type === 'authenticated') {
                                console.log('管理员已验证');
                            } else if (message.type === 'authentication_failed') {
                                console.error('管理员验证失败');
                                this.websocket.close();
                            }
                        } catch (error) {
                            console.error('解析WebSocket消息出错:', error);
                        }
                    };

                    this.websocket.onerror = (error) => {
                        console.error('管理员WebSocket错误:', error);
                        this.$message.error("WebSocket 连接失败，请稍后再试");
                    };

                    this.websocket.onclose = () => {
                        console.log('管理员WebSocket连接已关闭');
                        this.$store.state.websocket = null;
                    };

                    // 最后再设置到store中
                    this.$store.state.websocket = this.websocket;
                }, 500); // 延迟500毫秒确保token已设置

                // 使用replace而不是push，避免导航守卫重定向问题
                this.$router.replace('/admin/adminPage').finally(() => {
                    // 在路由跳转完成后再结束loading状态
                    setTimeout(() => {
                        this.loading = false;
                        this.isNavigating = false; // 导航完成后重置标记
                    }, 300);
                });
            }).catch((error) => {
                console.error('获取用户信息失败:', error);
                this.$message.error("获取用户信息失败，请稍后再试");
                this.loading = false;
            });
        },
    }
};
</script>
<style scoped>
.button-container {
    display: flex;
    justify-content: center; /* 居中对齐 */
    align-items: center; /* 垂直居中对齐 */
    gap: 20px; /* 控制注册和忘记密码链接与登录按钮之间的距离 */
}
.background-image, .form-container, footer {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-size: 16px;
}
.component-background {
    background-image: url('https://doocassell.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241219204613.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
.background-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
}

.login-form {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh; /* Make the container take up the full viewport height */
}

.register-link {
    margin-right: auto;
}

.forgot-password-link {
    margin-right: auto;
}

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
    padding: 10px;
}
/* 遮罩层样式 */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.wrapper {
    --input-focus: #2d8cf0;
    --font-color: #323232;
    --font-color-sub: #666;
    --bg-color: #fff;
    --bg-color-alt: #666;
    --main-color: #323232;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.switch {
    transform: translateY(-200px);
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 30px;
    width: 50px;
    height: 20px;
}

.card-side::before {
    position: absolute;
    content: '用户登录';
    left: -70px;
    top: 0;
    width: 100px;
    text-decoration: underline;
    color: var(--font-color);
    font-weight: 600;
}

.card-side::after {
    position: absolute;
    content: '管理员登录';
    left: 70px;
    top: 0;
    width: 100px;
    text-decoration: none;
    color: var(--font-color);
    font-weight: 600;
}

.toggle {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    box-sizing: border-box;
    border-radius: 5px;
    border: 2px solid var(--main-color);
    box-shadow: 4px 4px var(--main-color);
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--bg-color);
    transition: 0.3s;
}

.slider:before {
    box-sizing: border-box;
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    border: 2px solid var(--main-color);
    border-radius: 5px;
    left: -2px;
    bottom: 2px;
    background-color: var(--bg-color);
    box-shadow: 0 3px 0 var(--main-color);
    transition: 0.3s;
}

.toggle:checked + .slider {
    background-color: var(--input-focus);
}

.toggle:checked + .slider:before {
    transform: translateX(30px);
}

.toggle:checked ~ .card-side:before {
    text-decoration: none;
}

.toggle:checked ~ .card-side:after {
    text-decoration: underline;
}

/* card */
.flip-card__inner {
    width: 400px;
    height: 350px;
    position: relative;
    background-color: transparent;
    perspective: 1000px;
    text-align: center;
    transition: transform 0.8s;
    transform-style: preserve-3d;
}

.toggle:checked ~ .flip-card__inner {
    transform: rotateY(180deg);
}

.toggle:checked ~ .flip-card__front {
    box-shadow: none;
}

.flip-card__front, .flip-card__back {
    padding: 20px;
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: center;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    background: lightgrey;
    gap: 20px;
    width: 100%;
    border-radius: 5px;
    border: 2px solid var(--main-color);
    box-shadow: 4px 4px var(--main-color);
}

.flip-card__back {
    width: 100%;
    transform: rotateY(180deg);
}

.flip-card__form {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
}

.title {
    margin: 20px 0 20px 0;
    font-size: 25px;
    font-weight: 900;
    text-align: center;
    color: var(--main-color);
}

.flip-card__input {
    width: 250px;
    height: 40px;
    border-radius: 5px;
    border: 2px solid var(--main-color);
    background-color: var(--bg-color);
    box-shadow: 4px 4px var(--main-color);
    font-size: 15px;
    font-weight: 600;
    color: var(--font-color);
    padding: 5px 10px;
    outline: none;
}

.flip-card__input::placeholder {
    color: var(--font-color-sub);
    opacity: 0.8;
}

.flip-card__input:focus {
    border: 2px solid var(--input-focus);
}

.flip-card__btn:active, .button-confirm:active {
    box-shadow: 0px 0px var(--main-color);
    transform: translate(3px, 3px);
}

.flip-card__btn {
    margin: 0; /* 移除原有的上下外边距 */
    width: 120px;
    height: 40px;
    border-radius: 5px;
    border: 2px solid var(--main-color);
    background-color: var(--bg-color);
    box-shadow: 4px 4px var(--main-color);
    font-size: 17px;
    font-weight: 600;
    color: var(--font-color);
    cursor: pointer;
}

</style>

